package com.yaoxiaoqing.basis;

import java.util.Random;


public class ArrayMethods {
    public static void main(String[] args) {
        //复制数组
        copyArr();
        //数组反转
        reverseArr();
        //随机1-30不重复
        randomInt();
        //线性查找 查找（或搜索）
        linearSearch();
        //二分法查找
        binarySearch();

    }

    public static  void  copyArr(){
        int[] arr1, arr2;
        arr1 = new int[]{2, 5, 7, 11, 13, 17, 19}; //数组复制
        arr2 = new int[arr1.length];
        for (int i = 0; i < arr2.length; i++) {
            arr2[i] = arr1[i];
        }
    }

    public  static  void  reverseArr(){
//        int[] arr = new int[]{2, 5, 7, 11, 13, 17, 19};
//        for (int i = 0; i < arr.length/2; i++) {
//            int temp = arr[arr.length - 1 - i];
//            arr[arr.length - 1 - i] = arr[i];
//            arr[i] = temp;
//        }
        int[] arr = new int[]{2, 5, 7, 11, 13, 17, 19};
        for (int i = 0,j=arr.length-1; i < j; i++,j--) {
            int temp = arr[j];
            arr[i]=arr[j];
            arr[j]=temp;
        }
    }

    // 创建一个长度为 6 的 int 型数组，要求取值为 1-30，同时元素值各不相同
    public static void randomInt(){
        int[] arr = new int[30];
        java.util.Random r = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = r.nextInt(30)+1;
            for (int j = 0; j < i; j++) {
                if(arr[i]==arr[j]){
                    i--;
                    break;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }

    public  static  void  linearSearch(){
        String[] arr = new String[]{"SS","QQ","YY","XX","TT","KK","EE","GG"};
        String dest = "BB";//要查找的元素
        dest = "QQ";

        boolean isFlag = true;

        //比较两个字符串是否相等，你需要使用equals()方法。
        for (int i = 0; i < arr.length; i++) {
            if(dest.equals(arr[i])){
                System.out.println("找到了指定元素，位置为：" + i);
                isFlag = false;
                break;
            }
        }
        if(isFlag){
            System.out.println("很遗憾，没找到");
        }
    }

    public static void binarySearch(){
       //二分法查找： 前提：所要查找的数组必须有序
       int[] arr= new int[]{-98,-34,2,34,54,66,79,105,210,333};

       int dest = 34;
       int head = 0;//初始的首索引
       int end = arr.length - 1;//初始的末索引

       boolean isFlag = true;
       while (head<=end){
           int middle = (head + end) / 2; //整数相除会自动取整，保留整数部分，不会四舍五入

           if(dest==arr[middle]){
               System.out.println("二分法找到指定元素，位置为：" + middle);
               isFlag = false;
               break;
           }else if(arr[middle]>dest){
               end = middle - 1;
           }else{//arr[middle]<dest
               head = middle + 1;
           }
       }

       if(isFlag){
           System.out.println("很遗憾，没找到");
       }
    }

}
